﻿using Common.Core.Base;
using Common.Core.Extensions;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Logging;
using System.Text;

namespace Common.Core.Filters
{
    public class HttpGlobalExceptionFilter : ExceptionFilterAttribute, IExceptionFilter
    {
        private readonly ILogger<HttpGlobalExceptionFilter> _logger;
        public HttpGlobalExceptionFilter(ILogger<HttpGlobalExceptionFilter> logger)
        {
            _logger = logger;
        }

        public override void OnException(ExceptionContext context)
        {
            // 内容太多
            StringBuilder errorDetail = new StringBuilder();
            errorDetail.AppendLine($"Source：{context.Exception.Source}");
            errorDetail.AppendLine($"Host：{context.HttpContext.Request.Host}");
            errorDetail.AppendLine($"Path：{context.HttpContext.Request.Path}");
            errorDetail.AppendLine($"Query：{context.HttpContext.Request.QueryString}");
            var body = "";
            using (StreamReader reader = new StreamReader(context.HttpContext.Request.Body, Encoding.UTF8, true, 1024, true))
            {
                body = reader.ReadToEndAsync().Result;
            }
            errorDetail.AppendLine($"PostData：{body}");
            errorDetail.AppendLine($"Headers：{context.HttpContext.Request.Headers.ToJson()}");
            errorDetail.AppendLine($"Error Message：{context.Exception.Message}");
            errorDetail.AppendLine($"Error StackTrace：{context.Exception.StackTrace}");

            _logger.LogError(errorDetail.ToString());

            //拦截处理
            if (!context.ExceptionHandled)
            {
                var jsonResult = new JsonResult(new Result()
                {
                    Code = "500",
                    Msg = context.Exception.Message

                });
                jsonResult.StatusCode = 500;
                context.Result = jsonResult;
                context.ExceptionHandled = true;
            }
        }
    }
}
